﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using InTheHand.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfBluetooth.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class MainWindowModel : ObservableObject
    {
        /// <summary>
        /// 查找
        /// </summary>
        public ICommand SelectBluetooth { get; set; }
        /// <summary>
        /// 蓝牙列表
        /// </summary>
        private ObservableCollection<BluetoothMode> _BluetoothList;
        /// <summary>
        /// 蓝牙列表
        /// </summary>
        public ObservableCollection<BluetoothMode> BluetoothList { get => _BluetoothList; set => SetProperty(ref _BluetoothList, value); }
        /// <summary>
        /// 向ui添加蓝牙
        /// </summary>
        public Action<BluetoothMode> AddBlueTooth { get; set; }

        /// <summary>
        /// 蓝牙客户端
        /// </summary>
        BluetoothClient client { get; set; }
        public MainWindowModel()
        {
            client = new BluetoothClient();
            //SelectBluetooth = new AsyncRelayCommand(SelectBluetoothMethod);
            BluetoothList = new ObservableCollection<BluetoothMode>();
            SelectBluetooth = new RelayCommand(SelectBluetoothMethod);
        }



        private void SelectBluetoothMethod()
        {
           
            BluetoothList.Clear();
            Task.Factory.StartNew(() =>
            {
                var devices = client.DiscoverDevices();
                foreach (BluetoothDeviceInfo d in devices)
                {
                    BluetoothMode bluetoothMode = new BluetoothMode();
                    bluetoothMode.name = d.DeviceName;
                    bluetoothMode.bluetoothDeviceInfo = d;
                    bluetoothMode.client=client;
                    AddBlueTooth?.Invoke(bluetoothMode);
                }
            });
        }
    }
}
